import { Form, InputNumber, message, Modal, Select, Spin } from 'antd';
import type { FormInstance } from 'antd/es/form/Form';
import { FC, forwardRef, Ref, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { getFormulaDetail, saveFormulaSet } from './data';
interface Props {
  relatedType: number; //1车辆相关，2司机相关，3驾驶行为
  innerRef: Ref<{ showModal: (params: any) => void } | undefined>;
  onChange: (list: any) => void;
}
export type JobPorpsType = {
  positionId?: string;
  positionName?: string;
};

//*表单 */
type FormProps = {
  id?: string;
  /**
   * 公式
   */
  calculationRules?: number;
};

const FormulaSetForm = forwardRef<FormInstance<any>, FormProps>(({ id, calculationRules }, ref) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [initialValues, setInitValue] = useState<any>();
  useImperativeHandle(ref, () => form, [form]);
  /**
   * 监测会员类型的改变
   */
  const formType = Form.useWatch('formType', form);

  useEffect(() => {
    form.setFieldsValue(undefined);
    calculationRules
      ? form.setFieldsValue({
          formType: calculationRules,
          formulaName: calculationRules == 2 ? '计算公式A' : calculationRules == 3 ? '计算公式B' : '计算公式C',
        })
      : null;
    if (id) {
      setLoading(true);
      getFormulaDetail({ factorId: id }).then((res) => {
        setLoading(false);
        const timeUnit = calculationRules == 3 ? '周' : '日';
        if (res.code == '200' && res.data) {
          form.setFieldsValue({ timeUnit: res.data.timeUnit || timeUnit, ...res.data, keyIndex: res.data.denominator });
        } else {
          form.setFieldsValue({ timeUnit: timeUnit, ...res.data });
        }
      });
    } else {
      form.setFieldsValue({
        formType: 2,
        timeUnit: 1,
      });
    }
  }, []);
  return (
    <div style={{ position: 'relative' }}>
      <Form
        preserve={false}
        labelCol={{ style: { width: 120 } }}
        layout="horizontal"
        labelAlign="right"
        size="middle"
        initialValues={initialValues}
        form={form}
      >
        <Form.Item label="计算公式名" hidden name={'formulaName'}></Form.Item>
        <Form.Item
          label="计算公式"
          name={'formType'}
          rules={[
            {
              required: true,
            },
          ]}
          style={{ marginBottom: '24px' }}
        >
          <Select
            style={{ width: '300px' }}
            disabled={id ? true : false}
            options={[
              {
                label: '计算公式A',
                value: 2,
              },
              {
                label: '计算公式B',
                value: 3,
              },
              {
                label: '计算公式C',
                value: 4,
              },
            ]}
          ></Select>
        </Form.Item>
        {formType == 2 ? (
          <>
            <Form.Item
              label="变量最小值"
              name={'variableMinimumValue'}
              rules={[
                {
                  required: true,
                  message: '请输入变量最小值',
                },
                {
                  validator: (rule, value, callback) => {
                    if (value > form.getFieldValue('variableMaximumValue')) {
                      return callback('最小值不能大于最大值');
                    } else {
                      return callback();
                    }
                  },
                  validateTrigger: ['onSubmit'],
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              <InputNumber
                min={0}
                max={9999}
                precision={1}
                placeholder="请输入"
                style={{ width: '300px' }}
                controls={false}
              />
            </Form.Item>
            <Form.Item
              label="变量最大值"
              name={'variableMaximumValue'}
              rules={[
                {
                  required: true,
                  message: '请输入变量最大值',
                },
                {
                  validator: (rule, value, callback) => {
                    if (value < form.getFieldValue('variableMinimumValue')) {
                      return callback('最大值不能小于最小值');
                    } else {
                      return callback();
                    }
                  },
                  validateTrigger: ['onSubmit'],
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              <InputNumber
                min={0}
                max={9999}
                precision={1}
                placeholder="请输入"
                style={{ width: '300px' }}
                controls={false}
              />
            </Form.Item>
            <Form.Item
              label="得分最小值"
              name={'minimumScore'}
              rules={[
                {
                  required: true,
                  message: '请输入得分最小值',
                },
                {
                  validator: (rule, value, callback) => {
                    if (value > form.getFieldValue('maximumScore')) {
                      return callback('最小值不能大于最大值');
                    } else {
                      return callback();
                    }
                  },
                  validateTrigger: ['onSubmit'],
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              <InputNumber
                min={0}
                max={9999}
                precision={0}
                placeholder="请输入"
                style={{ width: '300px' }}
                controls={false}
              />
            </Form.Item>
            <Form.Item
              label="得分最大值"
              name={'maximumScore'}
              rules={[
                {
                  required: true,
                  message: '请输入得分最大值',
                },
                {
                  validator: (rule, value, callback) => {
                    if (value < form.getFieldValue('minimumScore')) {
                      return callback('最大值不能小于最小值');
                    } else {
                      return callback();
                    }
                  },
                  validateTrigger: ['onSubmit'],
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              <InputNumber
                min={0}
                max={9999}
                precision={0}
                placeholder="请输入"
                style={{ width: '300px' }}
                controls={false}
              />
            </Form.Item>
          </>
        ) : (
          <>
            <Form.Item
              label="得分最大值"
              name={'maximumScore'}
              rules={[
                {
                  required: true,
                  message: '请输入得分最大值',
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              <InputNumber
                min={0}
                max={9999}
                precision={0}
                placeholder="请输入"
                style={{ width: '300px' }}
                controls={false}
              />
            </Form.Item>
            <Form.Item
              label="时间单位"
              name={'timeUnit'}
              rules={[
                {
                  required: true,
                  message: '请选择时间单位',
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              {formType == 3 ? (
                <Select
                  style={{ width: '300px' }}
                  options={[
                    // {
                    //   label: '日',
                    //   value: '日',
                    // },
                    {
                      label: '周',
                      value: '周',
                    },
                    // {
                    //   label: '月',
                    //   value: 3,
                    // },
                    // {
                    //   label: '季',
                    //   value: 4,
                    // },
                    // {
                    //   label: '年',
                    //   value: 5,
                    // },
                  ]}
                ></Select>
              ) : (
                <Select
                  style={{ width: '300px' }}
                  options={[
                    {
                      label: '日',
                      value: '日',
                    },
                  ]}
                ></Select>
              )}
            </Form.Item>
            <Form.Item
              label="时间最大周期"
              name={'maxCycle'}
              rules={[
                {
                  required: true,
                  message: '请输入时间最大周期',
                },
              ]}
              style={{ marginBottom: '24px' }}
            >
              <InputNumber
                min={1}
                max={9999}
                precision={0}
                placeholder="请输入"
                style={{ width: '300px' }}
                controls={false}
              />
            </Form.Item>
            {formType == 3 ? (
              <>
                <Form.Item
                  label="发生次数最大值"
                  name={'occurrencesNumber'}
                  rules={[
                    {
                      required: true,
                      message: '请输入发生次数最大值',
                    },
                  ]}
                  style={{ marginBottom: '24px' }}
                >
                  <InputNumber
                    min={0}
                    max={9999}
                    precision={0}
                    placeholder="请输入"
                    style={{ width: '300px' }}
                    controls={false}
                  />
                </Form.Item>
                <Form.Item
                  label="指数"
                  name={'keyIndex'}
                  rules={[
                    {
                      required: true,
                      message: '',
                    },
                  ]}
                  style={{ height: '54px' }}
                >
                  <div className="flexr">
                    <span style={{ margin: '0 10px', fontSize: '16px', fontWeight: 'bold' }}>-</span>
                    <Form.Item
                      name={'numerator'}
                      rules={[
                        {
                          required: true,
                          message: '请输入分子',
                        },
                        {
                          validator: (rule, value, callback) => {
                            if (value > form.getFieldValue('denominator')) {
                              return callback('分子必须<=分母');
                            } else {
                              return callback();
                            }
                          },
                          validateTrigger: ['onSubmit'],
                        },
                      ]}
                    >
                      <InputNumber
                        min={0}
                        max={9999}
                        precision={0}
                        placeholder="分子"
                        style={{ width: '122px' }}
                        controls={false}
                      />
                    </Form.Item>
                    <span style={{ margin: '0 10px', fontSize: '16px', fontWeight: 'bold' }}>/</span>
                    <Form.Item
                      name={'denominator'}
                      rules={[
                        {
                          required: true,
                          message: '请输入分母',
                        },
                        {
                          validator: (rule, value, callback) => {
                            if (value < form.getFieldValue('numerator')) {
                              return callback('分母必须>=分子');
                            } else {
                              return callback();
                            }
                          },
                          validateTrigger: ['onSubmit'],
                        },
                      ]}
                    >
                      <InputNumber
                        min={1}
                        max={9999}
                        precision={0}
                        placeholder="分母"
                        style={{ width: '122px' }}
                        controls={false}
                      />
                    </Form.Item>
                  </div>
                </Form.Item>
              </>
            ) : null}
          </>
        )}
      </Form>
      {loading ? (
        <div className="flexr alc juc" style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
          <Spin spinning={loading}></Spin>
        </div>
      ) : null}
    </div>
  );
});

export const FormulaSetModel: FC<Props> = ({ innerRef, onChange, relatedType }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const form = useRef<FormInstance<any>>(null);
  const [id, setId] = useState<string>();
  const [calculationRules, setCalculationRules] = useState<number>();
  /*
   *打开弹窗
   */
  const showModal = ({ factorId, calculationRules }: { factorId: string; calculationRules: number }) => {
    factorId ? setId(factorId) : null;
    calculationRules ? setCalculationRules(calculationRules) : null;
    setIsOpen(true);
  };

  //提交表单
  const handleOk = async () => {
    try {
      await form.current?.validateFields();
      setConfirmLoading(true);
      //一些需要重装的数据
      const params = form.current?.getFieldsValue();
      params.relatedType = relatedType;
      params.factorId = id;
      params.signBit = '-'; // 符号位，目前写死'-'
      saveFormulaSet(params).then((res) => {
        setConfirmLoading(false);
        if (res.code == '200') {
          message.success('操作成功!');
          onChange && onChange(params);
          setIsOpen(false);
        }
      });
    } catch (error) {
      console.log(error, '打印看看');
    }
  };
  //初始化
  useEffect(() => {
    setConfirmLoading(false);
  }, [isOpen]);

  useImperativeHandle(innerRef, () => ({ showModal: showModal }));

  return (
    <Modal
      getContainer={false}
      className="formulaSet-model"
      title="公式设置"
      maskClosable={false}
      open={isOpen}
      onOk={handleOk}
      onCancel={() => setIsOpen(false)}
      width={480}
      centered
      okText="确定"
      destroyOnClose
      confirmLoading={confirmLoading}
      // cancelButtonProps={{ type: 'cancel' as any }}
    >
      <FormulaSetForm ref={form} id={id} calculationRules={calculationRules}></FormulaSetForm>
    </Modal>
  );
};
